from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List

from ..database import get_db
from ..models.models import Student, Interest, StudentPreference
from ..schemas import (
    StudentUpdate, StudentResponse,
    InterestCreate, InterestResponse,
    PreferenceCreate, PreferenceResponse
)
from .auth import get_current_user

router = APIRouter(
    prefix="/students",
    tags=["学生"]
)

@router.get("/me", response_model=StudentResponse)
async def read_student_me(
    current_user: Student = Depends(get_current_user)
):
    """获取当前登录学生信息"""
    return current_user

@router.put("/me", response_model=StudentResponse)
async def update_student_me(
    student_update: StudentUpdate,
    current_user: Student = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新当前登录学生信息"""
    for field, value in student_update.dict(exclude_unset=True).items():
        setattr(current_user, field, value)
    db.commit()
    db.refresh(current_user)
    return current_user

@router.get("/interests", response_model=List[InterestResponse])
async def list_interests(
    db: Session = Depends(get_db)
):
    """获取所有可选的兴趣爱好"""
    return db.query(Interest).all()

@router.post("/me/interests/{interest_id}", response_model=StudentResponse)
async def add_student_interest(
    interest_id: int,
    current_user: Student = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """添加兴趣爱好"""
    interest = db.query(Interest).filter(Interest.id == interest_id).first()
    if not interest:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="兴趣爱好不存在"
        )
    current_user.interests.append(interest)
    db.commit()
    db.refresh(current_user)
    return current_user

@router.delete("/me/interests/{interest_id}", response_model=StudentResponse)
async def remove_student_interest(
    interest_id: int,
    current_user: Student = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """移除兴趣爱好"""
    interest = db.query(Interest).filter(Interest.id == interest_id).first()
    if not interest:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="兴趣爱好不存在"
        )
    current_user.interests.remove(interest)
    db.commit()
    db.refresh(current_user)
    return current_user

@router.post("/me/preferences", response_model=PreferenceResponse)
async def create_student_preference(
    preference: PreferenceCreate,
    current_user: Student = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建室友偏好"""
    # 检查目标学生是否存在
    target_student = db.query(Student).filter(Student.id == preference.preferred_student_id).first()
    if not target_student:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="目标学生不存在"
        )
        
    # 检查是否已存在偏好设置
    existing_preference = (
        db.query(StudentPreference)
        .filter(
            StudentPreference.student_id == current_user.id,
            StudentPreference.preferred_student_id == preference.preferred_student_id
        )
        .first()
    )
    
    if existing_preference:
        # 更新现有偏好
        existing_preference.preference_level = preference.preference_level
        db.commit()
        db.refresh(existing_preference)
        return existing_preference
        
    # 创建新偏好
    db_preference = StudentPreference(
        student_id=current_user.id,
        preferred_student_id=preference.preferred_student_id,
        preference_level=preference.preference_level
    )
    db.add(db_preference)
    db.commit()
    db.refresh(db_preference)
    return db_preference

@router.get("/me/preferences", response_model=List[PreferenceResponse])
async def list_student_preferences(
    current_user: Student = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取所有室友偏好设置"""
    return current_user.preferences

@router.delete("/me/preferences/{preference_id}")
async def delete_student_preference(
    preference_id: int,
    current_user: Student = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除室友偏好"""
    preference = (
        db.query(StudentPreference)
        .filter(
            StudentPreference.id == preference_id,
            StudentPreference.student_id == current_user.id
        )
        .first()
    )
    
    if not preference:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="偏好设置不存在"
        )
        
    db.delete(preference)
    db.commit()
    return {"status": "success"} 